package com.bai.localshop.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.bai.localshop.context.BaseContext;
import com.bai.localshop.exception.BaseException;
import com.bai.localshop.mapper.UserMapper;
import com.bai.localshop.mapper.UserRoleMapper;
import com.bai.localshop.pojo.dto.UserPageQueryDTO;
import com.bai.localshop.pojo.dto.UserSaveDTO;
import com.bai.localshop.pojo.dto.UserUpdateDTO;
import com.bai.localshop.pojo.entity.User;
import com.bai.localshop.pojo.entity.UserRole;
import com.bai.localshop.pojo.vo.UserPageVO;
import com.bai.localshop.pojo.vo.UserDetailsVO;
import com.bai.localshop.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    private final UserMapper userMapper;
    private final UserRoleMapper userRoleMapper;


    /**
     * 分页查询用户
     *
     * @param requestParam
     * @return
     */
    @Override
    public IPage<UserPageVO> pageQuery(UserPageQueryDTO requestParam) {
        //设置默认分页查询参数
        int page = requestParam.getPage() != null ? requestParam.getPage() : 1;
        int pageSize = requestParam.getPageSize() != null ? requestParam.getPageSize() : 10;
        //执行分页查询
        IPage<UserPageVO> userPage = userMapper.selectUserPage(new Page<>(page, pageSize), requestParam);
        return userPage;
    }

    /**
     * 根据id查询用户信息
     */
    @Override
    public UserDetailsVO selectGetById(Long id) {
        User user = baseMapper.selectById(id);
        UserDetailsVO userDetailsVO = BeanUtil.toBean(user, UserDetailsVO.class);

        // 查询用户的角色信息
        LambdaQueryWrapper<UserRole> queryWrapper = Wrappers.lambdaQuery(UserRole.class)
                .eq(UserRole::getUserId, id);
        List<UserRole> userRoles = userRoleMapper.selectList(queryWrapper);
        List<Long> roleIds = userRoles.stream()
                .map(UserRole::getRoleId)
                .collect(Collectors.toList());
        // 修正角色名称判断逻辑
        if (!roleIds.isEmpty()) {
            // 假设角色ID为1的是管理员（根据实际情况调整）
            if (roleIds.contains(1L)) {
                userDetailsVO.setRoleName("管理员");
            } else {
                userDetailsVO.setRoleName("普通用户");
            }
        }
        return userDetailsVO;
    }

    /**
     * 新增用户
     */
    @Override
    public void save(UserSaveDTO userSaveDTO) {
        User user = BeanUtil.toBean(userSaveDTO, User.class);
        userMapper.insert(user);
        //像userRole表插入角色数据
        List<Long> roleIds = userSaveDTO.getRoleIds();
        roleIds.forEach(each -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(each);
            userRole.setUserId(user.getId());
            userRoleMapper.insert(userRole);
        });
    }

    /**
     * 根据id修改用户
     */
    @Override
    public void updateGetById(UserUpdateDTO requestParam) {
        if (requestParam.getId().equals(BaseContext.getCurrentId())){
            throw new BaseException("用户为当前登录用户，不能修改");
        }
        //修改用户基本属性
        LambdaUpdateWrapper<User> updateUserWrapper = Wrappers.lambdaUpdate(User.class)
                .set(User::getUsername, requestParam.getUsername())
                .set(User::getPhone, requestParam.getPhone())
                .set(User::getEmail, requestParam.getEmail())
                .set(User::getStatus, requestParam.getStatus())
                .eq(User::getId, requestParam.getId());
        int userUpdated = userMapper.update(updateUserWrapper);
        if (userUpdated == 0) {
            throw new BaseException("用户更新失败");
        }
        //删除原本角色
        LambdaQueryWrapper<UserRole> deleteWrapper = Wrappers.lambdaQuery(UserRole.class)
                .eq(UserRole::getUserId, requestParam.getId());
        userRoleMapper.delete(deleteWrapper);
        //插入新的角色
        requestParam.getRoleIds().forEach(each -> {
            UserRole userRole = new UserRole();
            userRole.setRoleId(each);
            userRole.setUserId(requestParam.getId());
            userRoleMapper.insert(userRole);
        });
    }

    /**
     * 根据id删除用户
     *
     * @param id
     */
    @Override
    public void deleteById(Long id) {
        if (id.equals(BaseContext.getCurrentId())){
            throw new BaseException("用户为当前登录用户，不能删除");
        }
        //删除用户基本属性
        baseMapper.deleteById(id);
        //删除用户角色属性
        LambdaQueryWrapper<UserRole> deleteWrapper = Wrappers.lambdaQuery(UserRole.class)
                .eq(UserRole::getUserId, id);
        userRoleMapper.delete(deleteWrapper);
    }

    /**
     * 更新用户状态
     */
    @Override
    public void updateStatus(Long id, Integer status) {
        if (id.equals(BaseContext.getCurrentId())){
            throw new BaseException("用户为当前登录用户，不能禁用");
        }
        LambdaUpdateWrapper<User> updateWrapper = Wrappers.lambdaUpdate(User.class)
                .set(User::getStatus, status)
                .eq(User::getId, id);
        int updated = userMapper.update(updateWrapper);
        if (updated == 0) {
            throw new BaseException("用户状态更新失败");
        }
    }

    /**
     * 重置用户密码
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void resetPassword(Long id) {
        User user = getById(id);
        if (user == null) {
            throw new BaseException("用户不存在");
        }
        //重置为默认密码 123456
        String defaultPassword = "123456";
        String encodedPassword = BCrypt.hashpw(defaultPassword, BCrypt.gensalt());
        //更新密码
        LambdaUpdateWrapper<User> updateWrapper = Wrappers.lambdaUpdate(User.class)
                .set(User::getPassword, encodedPassword)
                .eq(User::getId, id);
        int updated = userMapper.update(updateWrapper);
        if (updated == 0) {
            throw new BaseException("密码重置失败");
        }
    }
}